package com.study.interceptor;

import com.study.bean.SessionUser;
import com.study.bean.UserInfoTo;
import com.study.constant.CarConstant;
import com.study.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 执行目标方法之前，判断用户状态
 */
@Slf4j
@Component
public class CarInterceptor implements HandlerInterceptor {
    /**
     * ThreadLocal 同一个线程共享数据
     */

    public static ThreadLocal<UserInfoTo> localUser =
            new ThreadLocal<>();

    /**
     * 在目标方法执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO     
        //路径匹配
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/car", uri);

        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        SessionUser attribute = (SessionUser) session.getAttribute(SysUtils.LOGIN_NAME);
        if (attribute != null) {
            //    登录
            userInfoTo.setUserId(attribute.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CarConstant.TEMP_USER_COOKIE)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                    break;
                }
            }
        }

        //TODO 没有临时用户分配一个临时用户|在业务执行之后把 临时用户发送给浏览器
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = SysUtils.getUUID();
            userInfoTo.setUserKey(uuid);
        }

        localUser.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后|业务执行之后把 临时用户发送给浏览器
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        UserInfoTo userInfoTo = localUser.get();

        //TODO 判断是否用 临时用户，没有才设置
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CarConstant.TEMP_USER_COOKIE, userInfoTo.getUserKey());
            cookie.setMaxAge(CarConstant.TEMP_USER_COOKIE_TIMEOUT);

            response.addCookie(cookie);
        }

    }
}
